<template>
  <div class="room-list-container">
    <!-- 顶部标题和筛选区域 -->
    <div class="header">
      <div class="title-section">
        <h1><i class="el-icon-office-building"></i> 酒店房间列表</h1>
        <p class="subtitle">浏览并预订您理想的住宿环境</p>
      </div>
      
      <div class="filter-section">
        <div class="filter-group">
          <div class="filter-row">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索房间号"
              class="search-input"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="el-icon-search"></i>
              </template>
            </el-input>
            
            <el-select 
              v-model="filterType" 
              placeholder="选择房间类型" 
              clearable 
              class="filter-select"
              @change="handleSearch"
            >
              <el-option
                v-for="type in roomTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
            
            <el-select 
              v-model="filterStatus" 
              placeholder="房间状态" 
              clearable 
              class="filter-select"
              @change="handleSearch"
            >
              <el-option
                v-for="status in roomStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </div>
          
          <div class="action-row">
            <el-button 
              type="primary" 
              icon="el-icon-search" 
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button 
              type="info" 
              icon="el-icon-refresh" 
              @click="resetFilters"
            >
              重置
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 房间列表展示区域 -->
    <div class="room-list">
      <div v-if="roomList.length === 0" class="empty-state">
        <!-- <img src="https://via.placeholder.com/300x200?text=No+Rooms" alt="No rooms found" /> -->
        <p>没有找到符合条件的房间</p>
        <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
      </div>
      
      <el-row :gutter="20" v-else>
        <el-col 
          v-for="room in roomList" 
          :key="room.id" 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6"
        >
          <el-card class="room-card">
            <div class="room-image">
              <img 
                :src="room.imageUrl || defaultRoomImage" 
                alt="房间图片"
                class="room-img"
              />
              <!-- <img src="../assets/images/logo.png" alt=""> -->
              <div class="room-status" :class="getStatusClass(room.status)">
                {{ getStatusText(room.status) }}
              </div>
              <div class="room-type">{{ room.type }}</div>
            </div>
            
            <div class="room-info">
              <div class="room-header">
                <h3 class="room-title">{{ room.roomNumber }}</h3>
                <div class="room-price">¥{{ room.price }}<span>/晚</span></div>
              </div>
              
              <div class="room-meta">
                <div class="meta-item">
                  <i class="el-icon-user"></i>
                  <span>容纳: {{ room.capacity }}人</span>
                </div>
                <div class="meta-item">
                  <i class="el-icon-s-home"></i>
                  <span>{{ room.size || '25-30' }}㎡</span>
                </div>
                <div class="meta-item">
                  <i class="el-icon-view"></i>
                  <span>{{ room.view || '城市景观' }}</span>
                </div>
              </div>
              
              <p class="room-desc">{{ room.description || '舒适宽敞的房间，配备现代化设施，提供高品质住宿体验' }}</p>
            </div>
            
            <div class="room-actions">
              <el-button 
                type="primary" 
                icon="el-icon-tickets" 
                :disabled="room.status !== 1"
                @click="openReserveDialog(room)"
                class="action-btn"
              >
                {{ room.status === 1 ? '立即预订' : '不可预订' }}
              </el-button>
              
              <el-button 
                :type="isRoomCollected(room.id) ? 'success' : 'default'" 
                :icon="isRoomCollected(room.id) ? 'el-icon-star-on' : 'el-icon-star-off'"
                @click="toggleCollection(room.id)"
                class="action-btn"
                circle
              >{{ isRoomCollected(room.id) ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="roomList.length > 0">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRooms"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 预订房间对话框 -->
    <el-dialog 
      title="预订房间" 
      :visible.sync="reserveDialogVisible" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="reserveForm" 
        :model="reserveForm" 
        :rules="reserveRules"
        label-width="100px"
      >
        <el-form-item label="房间信息" prop="roomInfo">
          <div class="reserve-room-info">
            <div class="reserve-room-title">{{ currentReserveRoom.roomNumber }} - {{ currentReserveRoom.type }}</div>
            <div class="reserve-room-meta">
              <span><i class="el-icon-user"></i> 容纳: {{ currentReserveRoom.capacity }}人</span>
              <span><i class="el-icon-money"></i> 价格: ¥{{ currentReserveRoom.price }}/晚</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="入住日期" prop="checkInDate">
          
          <el-date-picker clearable
            v-model="reserveForm.checkInDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择入住日期">
            :picker-options="roomCheckInOptions"
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="退房日期" prop="checkOutDate">
          <!-- <el-date-picker
            v-model="reserveForm.checkOutDate"
            type="date"
            placeholder="选择退房日期"
            :picker-options="checkOutOptions"
            value-format="YYYY-MM-DD"
            class="date-picker"
          /> -->
          <el-date-picker clearable
            v-model="reserveForm.checkOutDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退房日期">
            :picker-options="roomCheckOutOptions"
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="入住天数">
          <div class="stay-days">
            <el-tag type="info">{{ stayDays }} 晚</el-tag>
          </div>
        </el-form-item>
        
        <el-form-item label="总价">
          <div class="total-price">¥{{ totalPrice.toFixed(2) }}</div>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="reserveForm.paymentMethod" placeholder="请选择支付方式" class="payment-select">
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="银行卡" value="bankcard" />
            <el-option label="到店支付" value="cash" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="reserveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReserve" :loading="reserveLoading">确认预订</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom } from '@/api/Room.js';
import { addRoomorder,listRoomorder  } from '@/api/Roomorder.js';
import { addCollection, delCollectionInfo, listCollection } from '@/api/Collection.js';
import { getToken, getUserId } from '@/utils/auth.js';

export default {
  name: 'RoomList',
  data() {
    // 入住日期验证规则
    const validateCheckInDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择入住日期'));
      } else {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const selectedDate = new Date(value);
        
        if (selectedDate < today) {
          callback(new Error('入住日期不能早于今天'));
        } else {
          callback();
        }
      }
    };

    // 退房日期验证规则
    const validateCheckOutDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择退房日期'));
      } else if (!this.reserveForm.checkInDate) {
        callback(new Error('请先选择入住日期'));
      } else {
        const checkInDate = new Date(this.reserveForm.checkInDate);
        const checkOutDate = new Date(value);
        
        if (checkOutDate <= checkInDate) {
          callback(new Error('退房日期必须晚于入住日期'));
        } else {
          callback();
        }
      }
    };

    return {
       // 新增：存储现有订单数据
      existingOrders: [],
      // 房间列表数据
      roomList: [],
      totalRooms: 0,
      currentPage: 1,
      pageSize: 8,
      searchKeyword: '',
      filterStatus: null,
      filterType: null,
      
      // 收藏相关数据
      collectedRooms: [],
      
      // 预订对话框相关数据
      reserveDialogVisible: false,
      reserveLoading: false,
      currentReserveRoom: {},
      reserveForm: {
        checkInDate: '',
        checkOutDate: '',
        paymentMethod: 'alipay'
      },
      reserveRules: {
        checkInDate: [
          { required: true, validator: validateCheckInDate, trigger: 'change' }
        ],
        checkOutDate: [
          { required: true, validator: validateCheckOutDate, trigger: 'change' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      },
      
      // 默认房间图片
      defaultRoomImage: 'https://images.unsplash.com/photo-1611892440504-42a792e24d32?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80',
      
      // 房间状态选项
      roomStatusOptions: [
        { value: 1, label: '空闲' },
        { value: 0, label: '已预订' },
        { value: 2, label: '已入住' },
        { value: 3, label: '维修中' }
      ],
      
      // 房间类型选项
      roomTypeOptions: [
        { value: '单人间', label: '单人间' },
        { value: '双人间', label: '双人间' },
        { value: '大床房', label: '大床房' },
        { value: '套房', label: '套房' },
        { value: '总统套房', label: '总统套房' }
      ],
      
      // 日期选择器配置
      checkInOptions: {
        disabledDate: time => {
          // 以当天0点为基准，禁用所有过去的日期（含昨天及之前）
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 强制设为当天0点0分0秒
        return time.getTime() < today.getTime();
        }
      },
       roomCheckInOptions: {
        disabledDate: time => {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return time.getTime() < today.getTime();
        }
      },
      
      roomCheckOutOptions: {
        disabledDate: time => {
          if (!this.roomReserveForm.checkInDate) return true;
          const checkInDate = new Date(this.roomReserveForm.checkInDate);
          checkInDate.setHours(0, 0, 0, 0);
          return time.getTime() <= checkInDate.getTime();
        }
      },
    };
  },
  computed: {
    // 计算入住天数
    stayDays() {
      if (this.reserveForm.checkInDate && this.reserveForm.checkOutDate) {
        const start = new Date(this.reserveForm.checkInDate);
        const end = new Date(this.reserveForm.checkOutDate);
        const diffTime = Math.abs(end - start);
        return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      }
      return 0;
    },
    
    // 计算总价
    totalPrice() {
      if (this.currentReserveRoom && this.currentReserveRoom.price) {
        return this.stayDays * this.currentReserveRoom.price;
      }
      return 0;
    },
    
    // 计算退房日期选择器的禁用规则
    checkOutOptions() {
      return {
        disabledDate: time => {
          if (!this.reserveForm.checkInDate) return true;
          
          const checkInDate = new Date(this.reserveForm.checkInDate);
          checkInDate.setHours(0, 0, 0, 0);
          
          // 禁用入住日期之前的日期
          return time.getTime() < checkInDate.getTime();
        }
      };
    }
  },
  mounted() {
    this.fetchRooms();
    this.fetchCollections();
    this.fetchExistingOrders(); // 加载现有订单
  },
  methods: {
     async fetchExistingOrders() {
      try {
        const response = await listRoomorder();
        if (response.code === 200) {
          // 只保留状态为1（待支付）和2（已支付）的订单
          this.existingOrders = response.rows.filter(
            order => order.status === 1 || order.status === 2
          );
        }
      } catch (error) {
        console.error('获取现有订单失败:', error);
        this.$message.error('获取房间预订信息失败，请稍后重试');
      }
    },
    // 获取房间列表
    async fetchRooms() {
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          roomNumber: this.searchKeyword,
          type: this.filterType, // 使用单独的房间类型筛选
          status: this.filterStatus
        };
        
        const response = await listRoom(params);
        this.roomList = response.rows || [];
        this.totalRooms = response.total || 0;
      } catch (error) {
        console.error('获取房间列表失败:', error);
        this.$message.error('获取房间列表失败，请稍后重试');
      }
    },
    
    // 获取当前用户的收藏列表
    async fetchCollections() {
      // 检查登录状态
      if (!getToken()) return;
      
      try {
        const userId = getUserId();
        const params = {
          userId,
          itemType: 1 // 1表示房间类型
        };
        
        const response = await listCollection(params);
        this.collectedRooms = response.rows.map(item => item.itemId) || [];
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        this.$message.error('获取收藏列表失败');
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchRooms();
    },
    
    // 重置所有筛选条件
    resetFilters() {
      this.searchKeyword = '';
      this.filterType = null;
      this.filterStatus = null;
      this.currentPage = 1;
      this.fetchRooms();
    },
    
    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchRooms();
    },
    
    // 处理页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchRooms();
    },
    
    // 获取房间状态文本
    getStatusText(status) {
      const statusMap = {
        0: '已预订',
        1: '空闲',
        2: '已入住',
        3: '维修中'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取房间状态对应的CSS类
    getStatusClass(status) {
      const classMap = {
        0: 'status-reserved',
        1: 'status-available',
        2: 'status-occupied',
        3: 'status-maintenance'
      };
      return classMap[status] || '';
    },
    
    // 检查房间是否已被收藏
    isRoomCollected(roomId) {
      return this.collectedRooms.includes(roomId);
    },
    
    // 切换收藏状态
    async toggleCollection(roomId) {
      // 检查登录状态
      if (!getToken()) {
        this.$message.warning('请先登录后再进行收藏操作');
        this.$router.push('/login');
        return;
      }
      
      const userId = getUserId();
      
      try {
        if (this.isRoomCollected(roomId)) {
          // 如果已收藏，则取消收藏
          console.log("roomId="+roomId);
          await delCollectionInfo({
            userId,
            itemType: 1,
            itemId: roomId
          });
          
          // 从收藏列表中移除
          this.collectedRooms = this.collectedRooms.filter(id => id !== roomId);
          this.$message.success('已取消收藏');
        } else {
          // 如果未收藏，则添加收藏
          await addCollection({
            userId,
            itemType: 1, // 1表示房间类型
            itemId: roomId
          });
          
          // 添加到收藏列表
          this.collectedRooms.push(roomId);
          this.$message.success('收藏成功');
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },
    
    // 打开预订对话框
    openReserveDialog(room) {
      //console.log('点击了预订按钮', room)
      // 检查登录状态
      if (!getToken()) {
        this.$message.warning('请先登录后再预订房间');
        this.$router.push('/login');
        return;
      }
      
      // 检查房间状态
      if (room.status !== 1) {
        this.$message.warning('该房间当前不可预订');
        return;
      }
       // 刷新订单数据
       this.fetchExistingOrders();
       //console.log("存在的有效订单："+this.existingOrders);
      
      this.currentReserveRoom = { ...room };
      this.reserveForm = {
        checkInDate: '',
        checkOutDate: '',
        paymentMethod: 'alipay'
      };
      
      // 重置表单验证
      if (this.$refs.reserveForm) {
        this.$refs.reserveForm.resetFields();
      }
      this.$nextTick(() => {
    if (this.$refs.reserveForm) {
      this.$refs.reserveForm.resetFields();
    }
  });
      this.reserveDialogVisible = true;

    },
    
    // 提交预订
    async submitReserve() {
      
      // 验证表单
      try {
        await this.$refs.reserveForm.validate();
      } catch (error) {
        console.log('表单验证失败:', error);
        return;
      }
        // 新增：日期冲突检测
      const checkInDate = new Date(this.reserveForm.checkInDate);
      const checkOutDate = new Date(this.reserveForm.checkOutDate);
      // 检查当前房间的已有预订 
      const hasConflict = this.existingOrders.some(order => {
        // 只检查相同房间的订单
        if (order.roomId !== this.currentReserveRoom.id) return false;
        const existingCheckIn = new Date(order.checkInDate);
        const existingCheckOut = new Date(order.checkOutDate);
        // 检查日期是否重叠
        return (
          (checkInDate >= existingCheckIn && checkInDate < existingCheckOut) ||
          (checkOutDate > existingCheckIn && checkOutDate <= existingCheckOut) ||
          (checkInDate <= existingCheckIn && checkOutDate >= existingCheckOut) 
        );
      });
      
      if (hasConflict) {
        this.$message.error('该房间在选定日期内已被预订，请选择其他日期');
        return;
      }
      this.reserveLoading = true;
      
      try {
        const userId = getUserId();
        const roomId = this.currentReserveRoom.id;
        
        // 构建预订数据
        const orderData = {
          userId,
          roomId,
          checkInDate: this.reserveForm.checkInDate,
          checkOutDate: this.reserveForm.checkOutDate,
          paymentMethod: this.reserveForm.paymentMethod,
          totalPrice: this.totalPrice
        };
        
        // 调用预订API
        await addRoomorder(orderData);
        
        
        this.$message.success('预订成功！');
        this.reserveDialogVisible = false;
        
        // 刷新房间列表
        this.fetchRooms();
      } catch (error) {
        console.error('预订失败:', error);
        this.$message.error(`预订失败: ${error.message || '请稍后重试'}`);
      } finally {
        this.reserveLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.room-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
  padding: 25px 30px;
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.title-section {
  margin-bottom: 25px;
}

.title-section h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-section .subtitle {
  margin: 8px 0 0;
  font-size: 16px;
  opacity: 0.9;
}

.filter-section {
  background: rgba(255, 255, 255, 0.15);
  padding: 20px;
  border-radius: 10px;
  backdrop-filter: blur(5px);
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filter-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 220px;
}

.filter-select {
  flex: 1;
  min-width: 180px;
}

.action-row {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.room-list {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.empty-state img {
  max-width: 300px;
  margin-bottom: 25px;
  border-radius: 8px;
}

.empty-state p {
  font-size: 18px;
  color: #606266;
  margin-bottom: 25px;
}

.room-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.room-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.room-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.room-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.room-card:hover .room-img {
  transform: scale(1.08);
}

.room-status {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 6px 14px;
  border-radius: 20px;
  color: white;
  font-size: 13px;
  font-weight: bold;
  z-index: 2;
}

.room-type {
  position: absolute;
  bottom: 12px;
  left: 12px;
  padding: 6px 14px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 20px;
  color: white;
  font-size: 13px;
  font-weight: bold;
  z-index: 2;
}

.status-available {
  background: linear-gradient(45deg, #11998e, #38ef7d);
}

.status-reserved {
  background: linear-gradient(45deg, #ff416c, #ff4b2b);
}

.status-occupied {
  background: linear-gradient(45deg, #8e2de2, #4a00e0);
}

.status-maintenance {
  background: linear-gradient(45deg, #4b6cb7, #182848);
}

.room-info {
  padding: 20px;
  flex-grow: 1;
  background: white;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.room-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #303133;
}

.room-price {
  font-size: 22px;
  font-weight: 700;
  color: #e6a23c;
}

.room-price span {
  font-size: 14px;
  font-weight: normal;
  color: #909399;
}

.room-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.meta-item i {
  color: #409eff;
  font-size: 16px;
}

.room-desc {
  margin: 15px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.room-actions {
  padding: 0 20px 20px;
  display: flex;
  justify-content: space-between;
  gap: 10px;
  background: white;
}

.action-btn {
  flex: 1;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.reserve-room-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.reserve-room-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.reserve-room-meta {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #606266;
}

.date-picker {
  width: 100%;
}

.stay-days {
  font-size: 16px;
}

.total-price {
  font-size: 24px;
  font-weight: bold;
  color: #e6a23c;
}

.payment-select {
  width: 100%;
}

</style>